package cn.iocoder.yudao.module.picturebook.service.readingrecord;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.picturebook.controller.admin.book.vo.BookRespVO;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.book.BookDO;
import cn.iocoder.yudao.module.picturebook.service.book.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.picturebook.controller.admin.readingrecord.vo.*;
import cn.iocoder.yudao.module.picturebook.dal.dataobject.readingrecord.ReadingRecordDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.picturebook.dal.mysql.readingrecord.ReadingRecordMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.yudao.module.picturebook.enums.ErrorCodeConstants.*;

/**
 * 用户阅读记录 Service 实现类
 *
 * @author 芋道源码
 */
@Slf4j
@Service
@Validated
public class ReadingRecordServiceImpl implements ReadingRecordService {

    @Resource
    private ReadingRecordMapper readingRecordMapper;
    @Resource
    private BookService bookService;

    // ... existing code ...
    @Override
    public Long createReadingRecord(ReadingRecordSaveReqVO createReqVO) {
        // 参数校验
        if (createReqVO == null) {
            return null;
        }

        try {
            // 插入
            ReadingRecordDO readingRecord = BeanUtils.toBean(createReqVO, ReadingRecordDO.class);
            //获取当时时间日期
            LocalDate now = LocalDate.now();
            readingRecord.setReadDate(now);
            readingRecordMapper.insert(readingRecord);

            // 添加空值检查
            if (readingRecord.getId() == null) {
                return null;
            }

            // 返回
            return readingRecord.getId();
        } catch (Exception e) {
            log.error("[createReadingRecord] 创建阅读记录失败", e);
            return null;
        }
    }

    @Override
    public void updateReadingRecord(ReadingRecordSaveReqVO updateReqVO) {
        // 参数校验
        if (updateReqVO == null) {
            log.warn("[updateReadingRecord] 请求参数不能为空");
            return;
        }
        if (updateReqVO.getId() == null) {
            log.warn("[updateReadingRecord] 阅读记录ID不能为空");
            return;
        }

        // 校验存在
        if (readingRecordMapper.selectById(updateReqVO.getId()) == null) {
            log.warn("[updateReadingRecord] 阅读记录不存在，ID：{}", updateReqVO.getId());
            return;
        }
        // 更新
        ReadingRecordDO updateObj = BeanUtils.toBean(updateReqVO, ReadingRecordDO.class);
        readingRecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteReadingRecord(Long id) {
        // 参数校验
        if (id == null) {
            log.warn("[deleteReadingRecord] 阅读记录ID不能为空");
            return;
        }

        // 校验存在
        if (readingRecordMapper.selectById(id) == null) {
            log.warn("[deleteReadingRecord] 阅读记录不存在，ID：{}", id);
            return;
        }
        // 删除
        readingRecordMapper.deleteById(id);
    }

    @Override
    public void deleteReadingRecordListByIds(List<Long> ids) {
        // 参数校验
        if (ids == null || ids.isEmpty()) {
            log.warn("[deleteReadingRecordListByIds] 阅读记录ID列表不能为空");
            return;
        }

        // 删除
        readingRecordMapper.deleteByIds(ids);
    }


    private void validateReadingRecordExists(Long id) {
        // 参数校验
        if (id == null) {
            log.warn("[validateReadingRecordExists] 阅读记录ID不能为空");
            return;
        }

        if (readingRecordMapper.selectById(id) == null) {
            log.warn("[validateReadingRecordExists] 阅读记录不存在，ID：{}", id);
            return;
        }
    }

    @Override
    public ReadingRecordDO getReadingRecord(Long id) {
        // 参数校验
        if (id == null) {
            log.warn("[getReadingRecord] 阅读记录ID不能为空");
            return null;
        }

        return readingRecordMapper.selectById(id);
    }

    @Override
    public PageResult<ReadingRecordRespVO> getReadingRecordPage(ReadingRecordPageReqVO pageReqVO) {
        // 参数校验
        if (pageReqVO == null) {
            log.warn("[getReadingRecordPage] 分页请求参数不能为空");
            return PageResult.empty();
        }

        try {
            // 查询阅读记录分页数据
            PageResult<ReadingRecordDO> readingRecordDOPageResult = readingRecordMapper.selectPage(pageReqVO);

            List<ReadingRecordDO> recordList = readingRecordDOPageResult.getList();
            if (recordList == null || recordList.isEmpty()) {
                return new PageResult<>(Collections.emptyList(), readingRecordDOPageResult.getTotal());
            }
            List<ReadingRecordRespVO> respVOList = new ArrayList<>();
            //循环用book_Id查询书并转化
            for (ReadingRecordDO record : recordList) {
                if (record != null) {
                    BookDO book = null;
                    try {
                        book = bookService.getBook(record.getBookId());
                    } catch (Exception e) {
                        log.warn("[getReadingRecordPage] 获取书籍信息失败，bookId: {}", record.getBookId(), e);
                    }
                    ReadingRecordRespVO respVO = BeanUtils.toBean(record, ReadingRecordRespVO.class);
                    respVO.setBook(book);
                    respVOList.add(respVO);
                }
            }
            return new PageResult<>(respVOList, readingRecordDOPageResult.getTotal());
        } catch (Exception e) {
            log.error("[getReadingRecordPage] 获取阅读记录分页数据失败", e);
            return PageResult.empty();
        }
    }


    @Override
    public void deleteFavorites(Long bookId, Long userId) {
        // 参数校验
        if (bookId == null || userId == null) {
            log.warn("[deleteFavorites] 参数校验失败，bookId: {}, userId: {}", bookId, userId);
            return;
        }

        readingRecordMapper.deleteFavorites(bookId, userId);
    }

    @Override
    public ReadingRecordDO getReadingRecord(Long userId, Long bookId) {
        // 参数校验
        if (userId == null || bookId == null) {
            log.warn("[getReadingRecord] 参数校验失败，userId: {}, bookId: {}", userId, bookId);
            return null;
        }

        return readingRecordMapper.getReadingRecord(userId, bookId);
    }

    @Override
    public void updateReadingRecord(ReadingRecordDO readingRecord) {
        // 参数校验
        if (readingRecord == null) {
            log.warn("[updateReadingRecord] 阅读记录对象不能为空");
            return;
        }
        if (readingRecord.getId() == null) {
            log.warn("[updateReadingRecord] 阅读记录ID不能为空");
            return;
        }

        readingRecordMapper.updateReadingRecord(readingRecord);
    }

    @Override
    public String getReadingRecordCount(Long userId) {
        // 参数校验
        if (userId == null) {
            log.warn("[getReadingRecordCount] 用户ID不能为空");
            return "0-0";
        }

        try {
            //统计当天阅读记录总数根据updateTime
            //获取当前时间
            LocalDateTime now = LocalDateTime.now();
            //保留年月日
            now = now.withHour(0).withMinute(0).withSecond(0).withNano(0);
            int DayCount = readingRecordMapper.getDayCount(userId, now);
            log.info("今日阅读数：{}", DayCount);

            //获取本周阅读记录总数
            //获取七天前的时间
            //获取当天时间
            now = LocalDateTime.now();
            LocalDateTime weekAgo = now.minusDays(7);
            int WeekCount = readingRecordMapper.getWeekCount(userId, weekAgo, now);
            return DayCount + "-" + WeekCount;
        } catch (Exception e) {
            log.error("[getReadingRecordCount] 获取阅读记录统计失败，userId: {}", userId, e);
            return "0-0";
        }
    }

    @Override
    public ReadIngRecordDataRespVO getReadingRecordData(Long userId) {
        // 参数校验
        if (userId == null) {
            log.warn("[getReadingRecordData] 用户ID不能为空");
            return new ReadIngRecordDataRespVO(0, 0, 0, 0, 0);
        }

        try {
            //第一步统计阅读总天数
            int totalDays = readingRecordMapper.getTotalDays(userId);
            //第二步统计阅读绘本的总数量
            int totalCount = readingRecordMapper.getTotalCount(userId);
            //第三步统计今日阅读绘本的总数量
            LocalDate today = LocalDate.now();
            int todayCount = readingRecordMapper.getTodayCount(userId, today);
            //第四步统计本周阅读绘本的总数量
            LocalDateTime weekAgo = LocalDateTime.now().minusDays(7);
            int weekCount = readingRecordMapper.getWeekCount(userId, weekAgo, LocalDateTime.now());
            //第五步统计本月阅读绘本的总数量
            int monthCount = readingRecordMapper.getWeekCount(userId, LocalDateTime.now().minusDays(30), LocalDateTime.now());
            //第六步返回结果
            return new ReadIngRecordDataRespVO(totalDays, totalCount, todayCount, weekCount, monthCount);
        } catch (Exception e) {
            log.error("[getReadingRecordData] 获取阅读记录数据失败，userId: {}", userId, e);
            return new ReadIngRecordDataRespVO(0, 0, 0, 0, 0);
        }
    }
// ... existing code ...

}